from flask import Flask
from flask_apscheduler import APScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
import configparser
import os
from utils.path_util import get_root_dir
from urllib.parse import quote
from application_factory import web, configure_service
from flask_sqlalchemy import SQLAlchemy
from flask_cors import *

db = SQLAlchemy()
cf = configparser.ConfigParser()
cf.read(os.path.join(get_root_dir(), "config.ini"))

secs = cf.sections()
host = cf.get("Mysql-Database", "host")
port = cf.get("Mysql-Database", "port")
user = cf.get("Mysql-Database", "user")
password = cf.get("Mysql-Database", "password")
db_name = cf.get("Mysql-Database", "db")

mysql_info = dict(
    host=host,
    port=port,
    dbname=db_name,
    username=user,
    password=password
)

MYSQL_URL = 'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (mysql_info['username'], quote(mysql_info['password']),
                                                             mysql_info['host'], mysql_info['port'],
                                                             mysql_info['dbname'])


# set configuration values
class Config:
    """Prod config."""
    """基础配置，导入所有配置中"""
    # 数据库自动提交数据
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True

    # 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
    # 这需要额外的内存， 如果不必要的可以禁用它。
    SQLALCHEMY_TRACK_MODIFICATIONS = True

    # apscheduler 配置信息
    JOBS = []
    SCHEDULER_JOBSTORES = {
        'default': SQLAlchemyJobStore(url=MYSQL_URL, tablename='apscheduler_jobs')
    }
    SCHEDULER_EXECUTORS = {'default': {'type': 'threadpool', 'max_workers': 100}}
    SCHEDULER_API_ENABLED = True


app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config.from_object(Config())
app.config['JSON_AS_ASCII'] = False
app.config['DEBUG'] = True
app.register_blueprint(web.web_bp, url_prefix='/web')
scheduler = APScheduler()
scheduler.scheduler.add_jobstore('sqlalchemy', url=MYSQL_URL)
scheduler.init_app(app)
scheduler.start()


if __name__ == '__main__':
    # 第一步：先找到宿主机的ip，然后把宿主机的ip更新进ftp.repo
    # configure_service.remote_source_configure()

    # 第二步：启动web server
    app.run(host='0.0.0.0', debug=True)

    # server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
    # server.serve_forever()
